import re
from vnpy.trader.setting import SETTINGS
from vnpy_ctastrategy import (
    CtaTemplate,
    TickData,
)

def afterMidNightIntradayFunc(tick: TickData, stag: CtaTemplate) :
    if stag.pos == 0 :
        return
    scurT = tick.datetime.strftime("%H:%M")
    if ( scurT >= '14:59' and scurT < '17:00' ) or \
       ( scurT >= stag.symbol_endtime and scurT < '06:00' ) :
        if stag.pos > 0:
            sprice = stag.curTick.bid_price_1-4*stag.contract.pricetick
            stag.sell(sprice, abs(stag.pos))
            stag.write_log('ordersending,symbol[{}],price[{}],卖平,日内多头出场'.format(
                           stag.vt_symbol, sprice) )
            stag.put_event()
        elif stag.pos < 0:
            sprice = stag.curTick.ask_price_1+4*stag.contract.pricetick
            stag.cover(sprice, abs(stag.pos))
            stag.write_log('ordersending,symbol[{}],price[{}],买平,日内空头出场'.format(
                           stag.vt_symbol, sprice) )
            stag.put_event()

def testIntradayFunc(tick: TickData, stag: CtaTemplate) :
    if stag.pos == 0 :
        return
    scurT = tick.datetime.strftime("%H:%M")
    if scurT >= stag.symbol_endtime and scurT < '24:00' :
        if stag.pos > 0:
            sprice = stag.curTick.bid_price_1-4*stag.contract.pricetick
            stag.sell(sprice, abs(stag.pos))
            stag.write_log('ordersending,symbol[{}],price[{}],卖平,日内多头出场'.format(
                           stag.vt_symbol, sprice) )
            stag.put_event()
        elif stag.pos < 0:
            sprice = stag.curTick.ask_price_1+4*stag.contract.pricetick
            stag.cover(sprice, abs(stag.pos))
            stag.write_log('ordersending,symbol[{}],price[{}],买平,日内空头出场'.format(
                           stag.vt_symbol, sprice) )
            stag.put_event()

def getIntradayFunc( stag: CtaTemplate ) :
    sres = re.search('[0-9]+', stag.vt_symbol)
    if not sres :
        return None
    skey = stag.vt_symbol[ 0:sres.start() ] + 'EndTime'
    if skey not in SETTINGS :
        return None
    stag.symbol_endtime = SETTINGS[skey]
    if stag.symbol_endtime > '00:00' and stag.symbol_endtime < '06:00' :
        return afterMidNightIntradayFunc
    else :
        return None


